package com.sais.manage.boot.platform.storage;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class IdempotentCodeStorage {

    private static Map<String, LocalDateTime> IDEMPOTENT_CODES = new HashMap<>();

    public static boolean hasIdempotentCode(String idempotentCode) {
        LocalDateTime localDateTime = IDEMPOTENT_CODES.get(idempotentCode);
        if (StringUtils.isEmpty(localDateTime)) {
            return false;
        }
        if (localDateTime.isBefore(LocalDateTime.now())) {
            IDEMPOTENT_CODES.remove(idempotentCode);
            return false;
        }
        return true;
    }

    public static boolean setIdempotentCode(String idempotentCode, Long second) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime plusSeconds = now.plusSeconds(second);
        IDEMPOTENT_CODES.put(idempotentCode, plusSeconds);
        return true;
    }

    public static boolean removeIdempotentCode(String idempotentCode) {
        IDEMPOTENT_CODES.remove(idempotentCode);
        return true;
    }

}
